// 消息路由模块
#pragma once
#include <iostream>
#include <vector>
#include <string>
#include "InetAddr.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include "ThreadPool.hpp"
#include <functional>
#include "LockGuard.hpp"

using task_t = function<void()>;
using namespace std;

class MessageRoute
{
private:
    // 检测addr用户是否存在于用户容器中
    bool isExists(const InetAddr &addr)
    {
        for (auto user : _online_user)
        {
            if (user == addr)
            {
                return true;
            }
        }
        return false;
    }

public:
    MessageRoute()
    {
        pthread_mutex_init(&_mutex, nullptr);
    }
    ~MessageRoute()
    {
        pthread_mutex_destroy(&_mutex);
    }
    // 新增用户
    void AddUser(const InetAddr &addr)
    {
        LockGuard lockguard(&_mutex);
        // 若用户存在则不新增
        if (isExists(addr) == true)
        {
            return;
        }
        _online_user.push_back(addr);
    }
    // 删除用户
    void DelUser(const InetAddr &addr)
    {
        LockGuard lockguard(&_mutex);
        auto iter = _online_user.begin();
        while (iter != _online_user.end())
        {
            if (*iter == addr)
            {
                _online_user.erase(iter);
                break;
            }
            iter++;
        }
    }
    // 消息转发
    void RouteHelper(int sockfd, string message, InetAddr who)
    {
        LockGuard lockguard(&_mutex);
        // 将消息遍历转发给所有用户
        for (auto user : _online_user)
        {
            string send_message = "\n[" + who.Ip() + ":" + to_string(who.Port()) + "]# " + message + "\n";
            struct sockaddr_in clientaddr = user.Addr();
            ::sendto(sockfd, send_message.c_str(), send_message.size(), 0, (struct sockaddr *)&clientaddr, sizeof(clientaddr));
        }
    }
    // 消息路由-将消息转发给所有用户
    void Route(int sockfd, string message, InetAddr who)
    {
        // 用户首次发消息时，还需要额外存储自己到管理用户的vector中
        AddUser(who); // 无脑插入

        if (message == "Q" || message == "QUIT")
        {
            DelUser(who);
        }
        // 构建任务对象,入队列，让线程池进行转发
        task_t t = bind(&MessageRoute::RouteHelper, this, sockfd, message, who);
        ThreadPool<task_t>::GetInstance()->Enqueue(t);
    }

private:
    vector<InetAddr> _online_user;
    pthread_mutex_t _mutex;
};